package com.ai_daily.aitiantian.util;

import android.text.Layout;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.widget.ScrollView;
import android.widget.TextView;

public class TextViewUtils {

    public static int getLineNumberOfTextIndex(TextView textView, int textIndex) {
        if (textView == null || textView.getText() == null) {
            return -1; // 无效的TextView或文本
        }

        CharSequence text = textView.getText();
        TextPaint paint = textView.getPaint();
        int textViewWidth = textView.getWidth();

        StaticLayout layout = new StaticLayout(text, paint, textViewWidth, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);

        for (int i = 0; i < layout.getLineCount(); i++) {
            int lineStart = layout.getLineStart(i);
            int lineEnd = layout.getLineEnd(i);

            if (textIndex >= lineStart && textIndex < lineEnd) {
                return i; // 找到了包含指定索引的行
            }
        }

        return -1; // 没有找到包含指定索引的行
    }

    public static void scrollToTextLine(ScrollView scrollView, int viewHeight, int lineHeight, int targetLine) {
        // 计算目标行的位置
        int scrollPosition = targetLine * lineHeight;

        // 确保滚动位置不会超过TextView的总高度
        if (scrollPosition > viewHeight) {
            scrollPosition = viewHeight;
        }
        // 滚动到目标位置
        scrollView.smoothScrollTo(0, scrollPosition);
    }
}
